package com.sikaryofficial.backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sikaryofficial.backend.domain.dto.req.BrandTasteEvaluateListReq;
import com.sikaryofficial.backend.domain.dto.req.BrandTasteEvaluateOwnerReq;
import com.sikaryofficial.backend.domain.dto.req.BrandTasteEvaluateReq;
import com.sikaryofficial.backend.domain.dto.req.content.ContentEvaluatePageReq;
import com.sikaryofficial.backend.domain.dto.resp.BrandTasteEvaluateDTO;
import com.sikaryofficial.backend.domain.entity.BrandTasteEvaluate;
import com.sikaryofficial.backend.domain.mapping.BrandTasteEvaluateMapping;
import com.sikaryofficial.backend.domain.vo.CountryAreaVO;
import com.sikaryofficial.backend.mapper.BrandTasteEvaluateMapper;
import com.sikaryofficial.backend.service.IAttachmentService;
import com.sikaryofficial.backend.service.IBrandTasteEvaluateService;
import com.sikaryofficial.backend.service.user.UserCacheService;
import com.sikaryofficial.common.core.exception.ServiceException;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.Objects;


/**
 * 品牌口味评价Service业务层处理
 *
 * @author qinjinyuan
 * @date 2023-10-27
 */
@Service
@Slf4j
public class BrandTasteEvaluateServiceImpl extends ServiceImpl<BrandTasteEvaluateMapper, BrandTasteEvaluate> implements IBrandTasteEvaluateService {

    @Autowired
    private BrandTasteEvaluateMapper brandTasteEvaluateMapper;
    @Autowired
    private IAttachmentService attachmentService;
    @Autowired
    private UserCacheService userCacheService;

    private BrandTasteEvaluate buildEntity(BrandTasteEvaluateReq req) {
        req.setEvaluateId(IdWorker.getId());
        BrandTasteEvaluate entity = BrandTasteEvaluateMapping.INSTANCE.coverReqToEntity(req);
        entity.setCreatedTime(new Date());
        entity.setCreatedBy(SecurityUtils.getUserId());
        entity.setCreatedName(userCacheService.getAccountById(SecurityUtils.getUserId()));
        return entity;
    }

    /**
     * @param customerPage
     * @param req
     * @return
     */
    @Override
    public IPage<BrandTasteEvaluateDTO> evaluateList(Page<BrandTasteEvaluateDTO> customerPage, BrandTasteEvaluateListReq req) {
        return brandTasteEvaluateMapper.evaluateList(customerPage, req, SecurityUtils.getUserId());
    }

    /**
     * 个人中心-我的评价列表数据
     *
     * @param customerPage
     * @param req
     * @return
     */
    @Override
    public IPage<BrandTasteEvaluateDTO> ownerList(Page<BrandTasteEvaluateDTO> customerPage, BrandTasteEvaluateOwnerReq req) {
        return brandTasteEvaluateMapper.ownerList(customerPage, req);
    }

    /**
     * 后台-内容管理-评价列表数据
     *
     * @param customerPage
     * @param req
     * @return
     */
    @Override
    public IPage<BrandTasteEvaluateDTO> backendContentList(Page<BrandTasteEvaluateDTO> customerPage, ContentEvaluatePageReq req) {
        return brandTasteEvaluateMapper.backendContentList(customerPage, req);
    }

    /**
     * 新增评价数据
     *
     * @param req
     * @return
     */
    @Override
    public boolean saveEvaluate(BrandTasteEvaluateReq req) {
        return this.save(buildEntity(req));
    }

    @Override
    public boolean saveEvaluate(BrandTasteEvaluateReq req, String ip, CountryAreaVO countryAreaVO) {
        BrandTasteEvaluate brandTasteEvaluate = buildEntity(req);
        // 新增需求，设置扩展字段值
        /**
         * ip查询优化的时候，可以扩展一个int类型字段
         *
         * SELECT INET_NTOA(ip_address) AS ip_address FROM devices;
         *
         * INSERT INTO devices (ip_address) VALUES (INET_ATON('192.168.0.1'));
         */
        brandTasteEvaluate.setIpAddress(ip);
        if (Objects.nonNull(countryAreaVO)) {
            brandTasteEvaluate.setCountry(countryAreaVO.getCountryName());
            brandTasteEvaluate.setArea(countryAreaVO.getArea());
            brandTasteEvaluate.setCity(countryAreaVO.getCity());
        }
        // email 看看
        brandTasteEvaluate.setEmail(userCacheService.getSignUserEmail(SecurityUtils.getUserId()));
        return this.save(brandTasteEvaluate);
    }

    /**
     * 更新评价数据
     *
     * @param req
     * @return
     */
    @Override
    public boolean updateEvaluate(BrandTasteEvaluateReq req) {
        Long userId = SecurityUtils.getUserId();
        LambdaUpdateWrapper<BrandTasteEvaluate> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(BrandTasteEvaluate::getEvaluateContent, req.getEvaluateContent())
                .set(BrandTasteEvaluate::getCompositeScore, req.getCompositeScore())
                .set(BrandTasteEvaluate::getUpdatedBy, userId)
                .set(BrandTasteEvaluate::getUpdatedTime, new Date())
                .eq(BrandTasteEvaluate::getEvaluateId, req.getEvaluateId());
        return this.update(updateWrapper);
    }

    /**
     * 删除评论
     *
     * @param evaluateIds
     * @return
     */
    @Override
    public boolean removeEvaluate(Long[] evaluateIds) {
        Long userId = SecurityUtils.getUserId();
        LambdaUpdateWrapper<BrandTasteEvaluate> updateWrapper
                = new LambdaUpdateWrapper<>();
        updateWrapper.set(BrandTasteEvaluate::getUpdatedBy, userId)
                .set(BrandTasteEvaluate::getUpdatedTime, new Date())
                .setSql(" deleted_version = evaluate_id ")
                .in(BrandTasteEvaluate::getEvaluateId, Arrays.asList(evaluateIds))
                .eq(BrandTasteEvaluate::getDeletedVersion, 0L);
        return this.update(updateWrapper);
    }

    /**
     * 根据ID获取评价详情
     *
     * @param evaluateId
     * @return
     */
    @Override
    public BrandTasteEvaluateDTO detail(Long evaluateId) {

        LambdaQueryWrapper<BrandTasteEvaluate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BrandTasteEvaluate::getDeletedVersion, 0L)
                .eq(BrandTasteEvaluate::getEvaluateId, evaluateId)
                .last(" limit 1");
        BrandTasteEvaluate mainEvaluate = this.getOne(queryWrapper);
        if (Objects.isNull(mainEvaluate)) {
            throw new ServiceException("the evaluate is not exist.");
        }
        BrandTasteEvaluateDTO mainEvaluateDTO = BrandTasteEvaluateMapping.INSTANCE.coverToDTO(mainEvaluate);
        // 填充附件
        mainEvaluateDTO.setAttachmentList(attachmentService.getAttachmentById(evaluateId));
        // 填充额外信息（品牌口味）

        return mainEvaluateDTO;
    }
}
